package com.malty.mall.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author luonankun
 * @date 2022/10/12
 **/
@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAspect {

    /**
     * 访问接口参数不全
     *
     * @param ex 参数缺失异常
     * @return 异常信息
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<String> missingServletRequestParameterException(HttpServletRequest request, MissingServletRequestParameterException ex) {
        String message = String.format("路径：%s 下的请求参数不全：%s", request.getRequestURI(), ex.getMessage());
        return CommonResult.failed(ResultCode.FAILED, message);
    }

    /**
     * 方法参数校验异常处理(bean 解析时参数校验出错的异常)
     *
     * @param notValidException 参数异常
     * @return 返回消息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException notValidException) {
        String msg = notValidException.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        log.warn("exception aspect:: respCode:{} ServiceExp message:{}", ResultCode.FAILED, msg, notValidException);
        return CommonResult.failed(msg);
    }

    /**
     * 表单形式校验处理失败抛出异常
     *
     * @param bindException bindException
     * @return 异常信息
     */
    @ExceptionHandler(value = BindException.class)
    public CommonResult<String> handleBindException(BindException bindException) {
        String message = Objects.requireNonNull(bindException.getBindingResult().getFieldError()).getDefaultMessage();
        return CommonResult.failed(message);
    }

    /**
     * 普通参数(非 java bean)校验出错时抛出
     *
     * @param violationException 参数校验异常
     * @return 异常信息
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<String> handleValidationException(ConstraintViolationException violationException) {
        String collect = violationException.getConstraintViolations().stream()
                .filter(Objects::nonNull).map(e -> e.getPropertyPath() + ": " + e.getMessage())
                .collect(Collectors.joining(", "));
        log.info("exception aspect:: respCode:{} ServiceExp message:{}", HttpStatus.BAD_REQUEST.value(), collect, violationException);
        return CommonResult.failed(collect);
    }


    @ExceptionHandler(Exception.class)
    public CommonResult<Exception> otherException(Exception exp) {
        log.error("exception aspect:: respCode:{} Exp message:{}", ResultCode.FAILED, exp.getMessage(), exp);
        return CommonResult.failed(ResultCode.FAILED, exp.getMessage());
    }
}
